package com.example.wx.service.wx;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.example.wx.common.WxConstant;
import com.example.wx.dao.entity.WxPublicMainDO;
import com.example.wx.dao.entity.WxPublicMainExtendDO;
import com.example.wx.dao.mapper.WxPublicAccountUserMapper;
import com.example.wx.dao.mapper.WxPublicMainMapper;
import com.example.wx.modle.accessToken.AccessToken;
import com.example.wx.modle.accessToken.Oauth2WebAccessToken;
import com.example.wx.modle.message.WxMessageTemplateDTO;
import com.example.wx.other.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class WxService {
    @Autowired
    private WxPublicMainMapper wxPublicMainMapper;
    @Autowired
    private WxPublicAccountUserMapper wxPublicAccountUserMapperDO;

    private static final String LOG_PREFIX = "微信公众号-WxService-";
    
    /**
     * @author: ZhangBin
     * @date: 2025/4/8 16:40
     * @description: 刷新基础accessToken
     */
    public void refreshAccessToken(Long id) {
        WxPublicMainDO wxPublicMainDO = wxPublicMainMapper.queryObject(id);
        if(Objects.isNull(wxPublicMainDO)){
           throw new BizException("公众号信息为空");
        }
        AccessToken accessToken = getAccessToken(wxPublicMainDO.getWxPublicAppId(), wxPublicMainDO.getWxPublicAppId());
        WxPublicMainExtendDO wxPublicMainExtendDO  = new WxPublicMainExtendDO();
        wxPublicMainExtendDO.setId(wxPublicMainDO.getId());
        wxPublicMainExtendDO.setWxAccessToken(accessToken.getAccess_token());
        wxPublicMainExtendDO.setWxAccessTokenExpire(accessToken.getExpires_in());
        wxPublicMainMapper.update(wxPublicMainExtendDO);
    }

    /**
     * @author: ZhangBin
     * @date: 2025/4/9 10:19
     * @description: 微信网页授权成功后获取openId
     */
    public Oauth2WebAccessToken getOauth2WebAccessToken(String appId,String appSecret,String code) {
        String accessTokenWebUrl = WxConstant.ACCESS_TOKEN_WEB_URL
                .replace("APPID", appId)
                .replace("SECRET", appSecret)
                .replace("CODE",code);
        Oauth2WebAccessToken oauth2WebAccessToken = null;
        try{
            log.info(LOG_PREFIX + "获取网页accessToken-START-accessTokenWebUrl={}",accessTokenWebUrl);
            String result = HttpUtil.get(accessTokenWebUrl);
            log.info(LOG_PREFIX + "获取网页accessToken-END-accessTokenWebUrl={},result={}",accessTokenWebUrl,result);
            oauth2WebAccessToken = JSON.parseObject(result, Oauth2WebAccessToken.class);
            if( Objects.isNull(oauth2WebAccessToken) || StringUtils.isBlank(oauth2WebAccessToken.getOpenid())){
                log.info(LOG_PREFIX + "获取网页accessToken-FAIL-oauth2WebAccessToken={}",JSON.toJSON(oauth2WebAccessToken));
                throw new BizException("获取网页accessToken失败");
            }
        }catch (Exception e){
            log.error(LOG_PREFIX + "获取网页accessToken-ERROR-oauth2WebAccessToken={}",JSON.toJSON(oauth2WebAccessToken),e);
            throw new BizException("获取网页accessToken失败");
        }
        return oauth2WebAccessToken;
    }

    public static List<WxMessageTemplateDTO.TemplateList> getTemplateList(String accessToken){
        String url  = WxConstant.TEMPLATE_GET_ALL_URL.replace("ACCESS_TOKEN",accessToken);
        String result = null;
        try{
            log.info(LOG_PREFIX + "获取基础accessToken-START-url={}",url);
            result = HttpUtil.get(url);
            log.info(LOG_PREFIX + "获取基础accessToken-END-url={},result={}",url,result);
            WxMessageTemplateDTO wxMessageTemplateDTOS = JSON.parseObject(result, WxMessageTemplateDTO.class);
            if(Objects.isNull(wxMessageTemplateDTOS) || CollectionUtils.isEmpty(wxMessageTemplateDTOS.getTemplate_list())){
                log.info(LOG_PREFIX + "获取消息模板为空-result={}",result);
                return new ArrayList<>();
            }
            return wxMessageTemplateDTOS.getTemplate_list();
        }catch (Exception e){
            log.info(LOG_PREFIX + "获取基础accessToken-ERROR-url={},result={}",url,result);
            throw new BizException("拉取消息模板失败");
        }
    }




    /**
     * @author: ZhangBin
     * @date: 2025/4/3 10:13
     * @description: 获取基础accessToken
     */
    public static AccessToken getAccessToken(String appId, String appSecret) {
        String url = WxConstant.ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
        String result = null;
        try{
            log.info(LOG_PREFIX + "获取基础accessToken-START-url={}",url);
            result = HttpUtil.get(url);
            log.info(LOG_PREFIX + "获取基础accessToken-END-url={},result={}",url,result);
            AccessToken accessToken = JSON.parseObject(result, AccessToken.class);
            if(Objects.isNull(accessToken) || StringUtils.isBlank(accessToken.getAccess_token())){
                throw new BizException("获取accessToken失败");
            }
            return accessToken;
        }catch (Exception e){
            log.info(LOG_PREFIX + "获取基础accessToken-ERROR-url={},result={}",url,result);
            throw e;
        }
    }


    public static void main(String[] args) {
        //{"access_token":"90_DV62Z9noWIylARjFgosF32lqW5BWB1Cr-CxIcwiZFP6xEGCt27MEOQdJXTld6txUq40j-eyKERW-1XeDAM2yA0EMJj5cZVoLKqUY6houhvS4KUVgSZjNzV1mgioOTNhAAAXCW","expires_in":7200}

        //AccessToken accessToken = getAccessToken("wx7fd8931d95e666e6", "72444af95c847e70552da3a4d79e43041");
        //log.info(JSON.toJSONString(accessToken));
        String url = "https://api.weixin.qq.com/cgi-bin/clear_quota/v2?appid=APPID&appsecret=APPSECRET"
                .replace("APPID", "wx7fd8931d95e666e6")
                .replace("APPSECRET", "72444af95c847e70552da3a4d79e43041");
        String result = HttpUtil.post(url,new HashMap<>());
        log.info(result);
    }

}
